package com.yugao.fintech.antelope.infra.file.modle;

import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import java.nio.charset.StandardCharsets;

/**
 * 文件上传

 */
@Data
@Accessors(chain = true)
public class FileUpload {
    private String bizType;
    private String fileName = "";
    private String fileExtension = "";
    private MultipartFile file;

    public FileUpload(MultipartFile file) {
        this.file = file;
    }

    public FileUpload init() {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        //判断是否为IE浏览器的文件名，IE浏览器下文件名会带有盘符信息

        // escaping dangerous characters to prevent XSS
        assert fileName != null;
        fileName = HtmlUtils.htmlEscape(fileName, StandardCharsets.UTF_8.name());

        // Check for Unix-style path
        int unixSep = fileName.lastIndexOf('/');
        // Check for Windows-style path
        int winSep = fileName.lastIndexOf('\\');
        // Cut off at latest possible point
        int pos = (Math.max(winSep, unixSep));
        if (pos != -1) {
            fileName = fileName.substring(pos + 1);
        }
        this.fileExtension = FilenameUtils.getExtension(fileName).toLowerCase();
        return this;
    }

    /**
     * 校验是否能上传
     */
    public FileUpload canUpload() {
        if (fileExtension.length() == 0 || fileExtension.equals("dll") || fileExtension.equals("exe") || fileExtension.equals("msi")) {
            throw new BizException(fileName + "不允许上传的文件");
        }
        return this;
    }
}
